﻿using System.Reflection;
using BaseData.CommonLib.Constants;
using Microsoft.Extensions.DependencyInjection;
using BaseData.RazorLib.Services;
using Microsoft.AspNetCore.Authorization;
using Swimj.CommonLib.Constants;

namespace BaseData.RazorLib
{
    public static class ServiceCollectionExtensions
    {
        public static void AddBaseDataBlazor(this IServiceCollection services)
        {
            services.AddScoped<ExampleJsInterop>();

            services.AddAuthorizationCore(options =>
            {
                RegisterPermissionClaims(options);
            });

            services.AddTransient<IMaterialCategoryService, MaterialCategoryService>();
            services.AddTransient<IMaterialService, MaterialService>();
            services.AddTransient<ICalculateUnitService, CalculateUnitService>();
            services.AddTransient<ICustomerService, CustomerService>();
            services.AddTransient<ISupplierService, SupplierService>();
            services.AddTransient<IWorkstationService, WorkstationService>();
            services.AddTransient<ISaleOrderService, SaleOrderService>();
        }

        private static void RegisterPermissionClaims(AuthorizationOptions options)
        {
            foreach (var prop in typeof(ApiRoutes).GetNestedTypes().SelectMany(c =>
                                 c.GetFields(BindingFlags.Public | BindingFlags.Static |
                                             BindingFlags.FlattenHierarchy)))
            {
                options.AddPolicy(prop.Name,
                    policy => policy.RequireClaim(ApplicationClaimTypes.Permission,
                        prop.Name));
            }
        }
    }
}